package com.example.huichaoliu;

import java.io.FileNotFoundException;

import org.json.JSONException;
import org.json.JSONObject;

import com.huichaoliu.app.R;
import com.huichaoliu.data.Config;
import com.huichaoliu.data.UserInfo;
import com.rederxu.AsyncTask.ImageTask;
import com.rederxu.request.HTTPRequest;
import com.rederxu.request.onRequestOverListener;
import com.rederxu.tools.BitmapUtil;
import com.rederxu.tools.Dialog;
import com.rederxu.views.RoundImageView;
import com.source.utils.Utils;

import android.app.Activity;
import android.content.ContentResolver;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;

public class MineFragment extends Fragment implements OnClickListener {

	private View v = null;
	private RoundImageView riv = null;
	private TextView tv_name = null;

	private final int CODE_BACK_FROM_CAMERA = 100;
	private final int CODE_BACK_FROM_ALBUM = 101;
	private final int CODE_SELECT_OVER = 102;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		if (v == null) {
			v = inflater.inflate(R.layout.fragment_mine, null);
		}
		ViewGroup parent = (ViewGroup) v.getParent();
		if (parent != null) {
			parent.removeView(v);
		}
		init();
		return v;
	}

	private void init() {
		v.findViewById(R.id.layout_more).setOnClickListener(this);
		v.findViewById(R.id.layout_order).setOnClickListener(this);
		v.findViewById(R.id.layout_share).setOnClickListener(this);
		v.findViewById(R.id.layout_info).setOnClickListener(this);
		v.findViewById(R.id.layout_coupons).setOnClickListener(this);

		tv_name = (TextView) v.findViewById(R.id.tv_name);
		riv = (RoundImageView) v.findViewById(R.id.riv_avatar);
		riv.setOnClickListener(this);
		
		if(!Config.isOnline(getActivity())){
			return;
		}
		initData();
	}

	private void initData() {
		UserInfo info = new UserInfo(getActivity());
		String avatar = info.getAvatar();
		if(avatar != null){
			ImageTask task = new ImageTask(riv,Config.getFolderImages(),null);
			task.execute(avatar);
		}
		tv_name.setText(info.getNickname());
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.layout_more:
			getActivity().startActivity(
					new Intent(getActivity(), MoreActivity.class));
			break;
		case R.id.layout_order:
			// showToast("[测试跳转]");
			// getActivity().startActivity(new
			// Intent(getActivity(),BankSelectActivity.class)); //ok
			getActivity().startActivity(
					new Intent(getActivity(), OrderActivity.class));
			break;
		case R.id.layout_share:
			// getActivity().startActivity(new
			// Intent(getActivity(),CouponsActivity.class));
			getActivity().startActivity(
					new Intent(getActivity(), ActivityShareActivity.class)); // ok
			// getActivity().startActivity(new
			// Intent(getActivity(),ShareActivity.class)); //ok
			// getActivity().startActivity(new
			// Intent(getActivity(),CollocationSchemeActivity.class)); //搭配方案ok
			// getActivity().startActivity(new
			// Intent(getActivity(),DesignerDetailActivity.class)); //
			// getActivity().startActivity(new
			// Intent(getActivity(),DesignerListActivity.class));
			// getActivity().startActivity(new
			// Intent(getActivity(),CallHelpActivity.class)); //ok
			// getActivity().startActivity(new
			// Intent(getActivity(),CameraFeedActivity.class)); //ok
			// getActivity().startActivity(new
			// Intent(getActivity(),PayActivity.class)); //ok
			// getActivity().startActivity(new
			// Intent(getActivity(),CommentActivity.class)); //ok
			// getActivity().startActivity(new
			// Intent(getActivity(),EnsureOrderActivity.class)); //ok
			// getActivity().startActivity(new
			// Intent(getActivity(),DetailHelpActivity.class)); //ok
			// getActivity().startActivity(new
			// Intent(getActivity(),BagActivity.class)); //ok
			break;
		case R.id.layout_info:
			getActivity().startActivity(
					new Intent(getActivity(), PersonalInfoActivity.class));
			break;
		case R.id.layout_coupons:
			getActivity().startActivity(
					new Intent(getActivity(), MyFeedsActivity.class));
			break;
		case R.id.riv_avatar:
			Dialog.showMessageDialog(getActivity(), "头像更换", "请选择图片来源", "相册",
					"相机", new DialogInterface.OnClickListener() {

						@Override
						public void onClick(DialogInterface dialog, int which) {
							if (DialogInterface.BUTTON_POSITIVE == which) {
								Intent intent = new Intent();
								/* 开启Pictures画面Type设定为image */
								intent.setType("image/*");
								/* 使用Intent.ACTION_GET_CONTENT这个Action */
								intent.setAction(Intent.ACTION_GET_CONTENT);
								/* 取得相片后返回本画面 */
								startActivityForResult(intent,
										CODE_BACK_FROM_ALBUM);
							} else {
								Intent intent = new Intent(
										MediaStore.ACTION_IMAGE_CAPTURE);
								startActivityForResult(intent,
										CODE_BACK_FROM_CAMERA);
							}
						}
					});
			break;
		}
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode,
			final Intent data) {
		if (requestCode == CODE_BACK_FROM_CAMERA
				&& resultCode == Activity.RESULT_OK && data != null) {
			// 照相机拍照完成并得到图片
			new Thread() {
				@Override
				public void run() {
					Bitmap photo = data.getParcelableExtra("data");
					String dir = Config.getFolderCache() + "file.png";
					BitmapUtil.saveBitmap(photo, dir);
					photo.recycle();
					// photo = getCompressedBitmap(dir);
					// photo.recycle();
					Message msg = new Message();
					msg.obj = dir;
					msg.what = CODE_SELECT_OVER;
					handler.sendMessage(msg);
					super.run();
				}
			}.start(); 
		} else if (requestCode == CODE_BACK_FROM_ALBUM
				&& resultCode == Activity.RESULT_OK && data != null) {
			// 相册取图完成
			new Thread() {
				@Override
				public void run() {
					Uri uri = data.getData();
					ContentResolver cr = getActivity().getContentResolver();
					try {
						Bitmap bitmap = BitmapFactory.decodeStream(cr
								.openInputStream(uri));
						String dir = Config.getFolderCache() + "file.png";
						BitmapUtil.saveBitmap(bitmap, dir);
						bitmap.recycle();
						Message msg = new Message();
						msg.obj = dir;
						msg.what = CODE_SELECT_OVER;
						handler.sendMessage(msg);
					} catch (FileNotFoundException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					super.run();
				}
			}.start();
		}
		super.onActivityResult(requestCode, resultCode, data);
	}

	private Handler handler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case CODE_SELECT_OVER:
				try {
					String path = (String) msg.obj;
					UserInfo info = new UserInfo(getActivity());
					JSONObject jo = new JSONObject();
					jo.put("userId", info.getUid());
					Bundle bundle = new Bundle();
					bundle.putString("request", Utils.requestParamsEncode(jo));
					Log.e("jo", jo.toString());
//					HTTPRequest.uploadFile(getActivity(),
//							Config.REQUEST_URLS.URL_USER_UPDATE_IMAGE, bundle,
//							path, new onRequestOverListener() {
//								@Override
//								public void onRequestOver(String result) {
//									Log.e("result", result);
//									try {
//										JSONObject jo = new JSONObject(result);
//										if (jo.getInt("code") != 0) {
//											showToast(jo.getString("message"));
//											return;
//										}
//										String filePath = jo.getString("image");
//										ImageTask it = new ImageTask(riv,
//												Config.getFolderImages(), null);
//										it.execute(filePath);
//									} catch (JSONException e) {
//										Log.e("result", result);
//										e.printStackTrace();
//									}
//								}
//							});
				} catch (Exception e) {
					e.printStackTrace();
				}
				break;
			}
			super.handleMessage(msg);
		}
	};

	private void showToast(String str) {
		Toast.makeText(getActivity(), str, Toast.LENGTH_SHORT).show();
	}
}
